<?php
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Input;
use Illuminate\Http\JsonResponse;
class CenterController extends BaseController {
    protected $layout = 'layouts.usercenter';
    public $user;
    public $info;
    public $user_group = 'center';
    
    public function __construct()
    {
    	parent::__construct();
    	
    	$user_id = Auth::user()->id;
    	$user = Auth::user();
    	$this->user = $user;
    	$this->user_group = $user->group->model;
    	View::share('realname', $this->user->realname);
		$this->unread_count = StationLetterUser::getUnreadCount();
    }

    public function welcome($account_type)
    {
    	if ($account_type == 'email') {
    		$parts = explode("@", $this->user->email);
    		$email_domain = $parts[1];
        	$this->layout->content = View::make('center.welcome.' . $account_type)->with(compact('email_domain'));
    	} else {
    		$this->layout->content = View::make('center.welcome.' . $account_type);
    	}
    }

	/**
	 * 我的问题
	 */
	public function question($status) {
		$status = ''; // 全部，已有回复，未回复

		$page = Input::get('page', 1);
		$rows_per_page = Input::get('rows_per_page', PaginationHelper::ROWS_PER_PAGE);
		$offset = ($page-1) * $rows_per_page;
		$order_by = Input::get('order_by', 'created_at');

		$questions = Post::getQuestions(
			null, 
			null, 
			null, 
			$offset, 
			$rows_per_page, 
			null, 
			$order_by, 
		    null,
			$this->user->id);
		return $this->makeView('center.question', $questions->toArray());
	}

    /**
     * 我的文章列表
     *  
     */
    public function articlesList() {
        $input=Input::get();
        $cate=array_key_exists('class',$input);
        $visi=array_key_exists('visibility',$input);
        $stat=array_key_exists('status',$input);

        $pass= true;
        // 分类 & 权限
        $querycondition = ['creator_id'=>Auth::user()->id];
//        $querycondition['status'] = $stat?2:1;
        if($visi)
        {
            $querycondition['visibility']=$input['visibility'];
        }
        if($cate)  
        {
            $querycondition['class']=$input['class'];
        }
        $data=Article::where($querycondition)->get()->toArray();
        for($i=0;$i<count($data);$i++){
            $article = Article::find($data[$i]['id']);
            $data[$i]['content'] = $article->getContent();
        	$classname = ArticleClass::find($data[$i]['class']);
        	if(empty($classname)){
        		$data[$i]['classname'] = '未分类';
        	}else{
        		$data[$i]['classname'] = $classname->name;
        	}
            $default = "img/default_imgs/[]".rand(1,19).".png";
            $data[$i]['img'] = UtilsHelper::getImage($data[$i]['img'], $default);
        }
        return $this->makeView('center.lawyer.blog.list', $data); 
    }
    

    /**
     * 创建文章
     * 
     * @param 
     */
    public function articleCreate(){
        if(Input::server ( 'REQUEST_METHOD' ) == 'POST') {      	
            //验证规则定义
            $rules = array (     
                'title'      => 'required|between:2,30',
                'info'      => 'required|between:2,140',
                'law_cat'      => 'required',
				'class'     =>   'required|in:368,369,370,371,374',
                'content'    => 'required|between:10,10000',
            );

            //错误提示定义
            $messages = array(
                'img.required'      => '请上传文章的缩略图',
                'law_cat.required'      => '请选择法律类型',
                'title.required'      => '请填写标题',
                'title.between'     => '标题长度在:min到:max之间',
                'info.required'      => '请填写文章的简介',
                // 'visibility.in'       => '格式错误',
                'class.required'   => '请填写分类',
                'class.in'         => '分类格式错误',
                'content.between'     => '内容长度在:min到:max之间',
                'content.required'    => '请填写内容'
            );

            //验证           
            $post = Input::all();
            $validator = Validator::make ( $post, $rules, $messages );

            if ($validator->fails()) {
                // the given data did not pass validation
                return $this->makeView(
                    'errors.400', 
                    $validator->errors(),
                    400
                );
            }
            //数据组装
            $post = Input::all();
            $post = UtilsHelper::filter_sensitive_word($post);             //敏感词过滤
            if(!empty($post['editorValue'])){
                $post['content']=$post['editorValue'];
                unset($post['editorValue']);
            }
            if(!isset($post['file_img'])&&!isset($post['img'])){
            	return $this->makeView('errors.400','请上传文章缩略图',400);
            }else{
            	$post['img'] = $post['file_img'];
            }
            try {
            	if($img = Input::file('img')){            	            	
            		$path = Config::get('app.upload_dir');
            		$dir = '/info'.date("/Y/m/", time());
            		$hashname = UtilsHelper::getHashName('img');
            		$img->move($path.$dir, $hashname);
            		$post['img'] = $path.$dir.$hashname; 
            	}        	            	
                $post['keys'] = '';
                $post['from_admin'] = false;
                $post['down_group'] = 0;
                $id = isset($post['id'])? $post['id']:null;
                $data = Article::storeArticle($post,$id);
				\Illuminate\Support\Facades\Event::fire('create_article', $data);
				return Redirect::to('center/lawyer/blog/list');
            } catch(Exception $ex) {
                Log::error($ex);
                return $this->makeView(
                    'errors.503', 
                    '创建博客失败，请稍后再试。',
                    503
                );
            }
        } else {
            $cates=Config::get('blog.category');
            $workScopes = UtilsHelper::workScope();
            $articleClasss = ArticleClass::all()->toArray();
            $this->layout->content = View::make('center.lawyer.blog.create')->with('cates',$cates)->with('workscopes', $workScopes)->with('articleClasss', $articleClasss);
        }
    }
    
    /**
     * 文章详情
     */
    public function articleView() {
        if(Input::server('REQUEST_METHOD')=='GET'){
            $input=Input::get('id');
            //验证id
            $validate=Article::validateId($input);
            if($validate)
                return $this->makeViewBlog('errors.400', $validate,true,400);
            //数据查询
            $row[]=DB::table('Article')->where('id',$input['id'])->first();
            //数据填充
            $data=Blog::padData($row);
            return $this->makeViewBlog('center.blog.view', $data[0]);  
        }        
    }

   /**
     * 帖子修改
     */
    public function articleMod() {
        if(Input::server('REQUEST_METHOD')=='POST'){
            $post = Input::all();
            //数据组装
            unset($post['_token']);
            if(!empty($post['editorValue'])){
                $post['content']=$post['editorValue'];
                unset($post['editorValue']);
            }
            //数据验证
            $validate=Blog::validateCreate($post);
            $validate1=Article::validateId($input);
            if($validate&&validate1)
                return $this->makeViewBlog('errors.400', $validate,true,400);
            //数据操作

           $bo=DB::table('Articles')->where('id', '=', $post['id'])->update($post); 
           //跳转
           if($bo!==false){
                $data='修改成功';
                return $this->makeRedirectBolg('center/blog/list',$data,201);
           }
        }
        
        $input=Input::get();
        $validate=Article::validateId($input);
        if($validate)
            return $this->makeViewBlog('errors.400', $validate,true,400);

        $row[]=DB::table('Articles')->where('id',$input['id'])->first();
        $line=$row[0];
        $cates=Config::get('blog.category');
        $this->layout->content = View::make('center.blog.mod',['cates'=>$cates,'line'=>$line]);
    }

    /**
     * 文章删除
     */
    public function articleDel() {
        
        $input=Input::get();
        $validate=Article::validateId($input);
        if($validate)
            return $this->makeViewBlog('errors.400', $validate,true,400);

        $bo=DB::table('Articles')->where('id', '=', $input['id'])->update(array('status'=>'2'));
        var_dump($bo);
        if($bo!==false){
            $data='删除成功';
            return $this->makeRedirectBolg('center/blog/list',$data,201);
            }
    }
        
    /**
     * 文章徹底彻底删除
     */
    public function articleEverDel() {
        
        $input=Input::get();
        $validate=Article::validateId($input);
        if($validate)
            return $this->makeViewBlog('errors.400', $validate,true,400);

        $bo=DB::table('Articles')->where('id', '=', $input['id'])->delete();
        if($bo){
            $data='彻底删除成功';
            return $this->makeRedirectBolg('center/blog/list',$data,201);
            }
    }


    /**
     * 我的收藏
     */
    public function collect() {
        $page = Input::get('page', 1);
        $rows_per_page = Input::get('rows_per_page', PaginationHelper::ROWS_PER_PAGE);
        $offset = ($page-1) * $rows_per_page;

    	$collects = Collect::where('creator_id',Auth::user()->id)
            ->take($rows_per_page)
            ->skip($offset)
	    	->orderBy('collects.created_at', 'DESC')
	    	->get();
    	$collectsArr = $collects->toArray();
        foreach($collectsArr as $key => &$collect) {
        	$result = $this->getCollect($collect['collect_type'], $collect['item_id']);
        	if (!empty($result)) {
        	    if (isset($result['creator_avatar'])) {
                    $collect['creator_avatar'] = UtilsHelper::getImage($result['creator_avatar'], "img/dfimg.png");
        	    }
                $collect['url'] = $this->getCollectUrl($collect['collect_type'], $collect['item_id']);
                $collect['title'] = $result['title'];
                $collect['content'] = $result['content'];
        	    if (isset($result['realname'])) {
                    $collect['creator_realname'] = $result['realname'];
        	    }
                $collect['show_img'] = false;
                if ($collect['collect_type'] == Collect::TYPE_ARTICLE) {
                    $default= "img/default_imgs/[]".rand(1,19).".png";
                    $collect['collect_img'] = UtilsHelper::getImage($result['img'],$default);
                    $collect['show_img'] = true;
                }
                $collect['collect_type_str'] = $this->getCollectTypeStr($collect['collect_type']);
        	} else {
        	    unset($collectsArr[$key]);
        	}
        }

        if (Route::is('center.lawyer.collect')) {
            $this->layout = View::make('layouts.lawyercenter');
        }
        $isLawyer = Lawyer::find(Auth::user()->id);
        if($isLawyer){
        	return $this->makeView('center.lawyer.collect', $collectsArr);
        }
    	return $this->makeView('center.collect', $collectsArr);
    }
    
    public function getCollect($collect_type, $item_id){
    	$result = array();
    	switch($collect_type) {
    		case Collect::TYPE_POST:
    			$post = Post::find($item_id);
    			if (is_a($post, 'Post')){
    				$result['title'] = $post->title;
                    $result['content'] = $post->content;
    				$user = User::find($post->creator_id);
    				if (is_a($user, 'User')){
    					$result['creator_avatar'] = $user->avatar;
    					$result['realname'] = $user->realname;
    				}
    			}
    			break;
    		case Collect::TYPE_ARTICLE:
    			$article = Article::find($item_id);
    			
    			if (is_a($article, 'Article')) {
    				$result['title'] = $article->title;
                    $result['content'] = $article->info;
                    $result['img'] = $article->img;
    				$user = User::find($article->creator_id);
    				if (is_a($user, 'User')){
    					$result['creator_avatar'] = $user->avatar;
    					$result['realname'] = $user->realname;
    				}
    			}
    			break;
    		default:return false;
    			
    	}
    	return $result;
    }
    
    protected function getCollectTypeStr($collect_type) {
        $name = "";
        switch($collect_type) {
            case Collect::TYPE_POST:
                $name = "咨询";
            break;
            case Collect::TYPE_ARTICLE:
                $name = "文章";
            break;
        }
        return $name;
    }

    protected function getCollectUrl($collect_type, $collect_id) {
        $url = "";
        switch($collect_type) {
            case Collect::TYPE_POST:
                $url = route('question.view', array('id' => $collect_id));
            break;
            case Collect::TYPE_ARTICLE:
                $url = route('knowledge.view', array('id' => $collect_id));
            break;
        }
        return $url;
    }
    
    public function deleteCollect($id){
        $collect = Collect::find($id);
        if(!$collect){
            return $this->makeView('errors.404','该收藏不存在',404);
        }

        try{
        	switch($collect->collect_type){
        		case Collect::TYPE_POST:
        			$result = Collect::delete_collect_post($collect);
        			break;
        		case Collect::TYPE_ARTICLE:
        			$result = Collect::delete_collect_article($collect);
        			break;
        	}
        }catch(Exception $ex){
            Log::error($ex);
            return $this->makeView('errors.503','服务器暂时无法响应，请稍后重试',503);
        }
        return $this->makeView('general.201','删除成功',201);
    }

    public function updateEmail() {
        $email = Input::get('email');
        if ($this->user->email != $email) {
            // 验证这个电话是否已经有人在用
            $rules['email'] = 'required|unique:user,email|email';
        } else {
            $rules['email'] = 'required|email';
        }
        $messages['email.required'] = '请输入邮箱';
        $messages['email.unique'] = '这个邮箱已经注册了';
        $messages['email.email'] = '邮箱格式不正确';

        $validator = Validator::make ( Input::all(), $rules, $messages );
        if ($validator->fails()) {
            // the given data did not pass validation
            return $this->makeView(
                'errors.400', 
                $validator->errors(),
                400
            );
        }

        try {
            $this->user->email = $email;
            $this->user->save ();

            // 创建或者更新activation token
            $activation = Activation::firstOrNew ( array (
                'email' => $this->user->email
            ) );
            $activation->token = str_random ( 40 );
            $activation->expired = time () + 86400 * 7;
            $activation->save ();
            Mail::send ( 'emails.auth.activation', [ 
                    'token' => $activation->token 
            ], function ($message) use($email) {
                $message->to ( $email )->subject ( '注册验证成功' );
            } );
        } catch(Exception $ex) {
            Log::error($ex);
            return $this->makeView(
                'errors.503', 
                '咨询律师失败，请稍后再试。',
                503
            );
        }
        return $this->makeView('center.update_email', '成功更改邮箱');
    }

    /**
     * 更新电话号码
     */
    public function updatePhone() {
        // mobile
        Validator::extend ( 'phone', function ($attr, $value, $parameters) {
            return preg_match ( "/^1[3-8]\d{9}$/", $value );
        } );
        
        Validator::extend ( 'phonecode', function ($attr, $value, $parameters) {
            return $value == '123456';

            /*
            $phone = Activation::where ( 'token', $value )->where ( 'expired', '>', time () )->pluck ( 'mobile' );
            if ($phone) {
                return Input::get ( 'phone' ) == $phone;
            } else {
                return false;
            }*/
        } );

        $phone = Input::get('phone');
        
        if ($this->user->phone != $phone) {
            // 验证这个电话是否已经有人在用
            $rules['phone']='required|phone|unique:user,phone';
        } else {
            $rules['phone']='required|phone';
        }

        $messages['phone.required']='手机号码没有填写';
        $messages['phone.phone']='手机号格式不正确';
        $messages['phone.unique'] = '这个手机号已经注册了';
        $rules['phonecode'] = 'required|phonecode';
        $messages['phonecode.required']='手机验证码没有填写';
        $messages['phonecode.phonecode'] = '手机验证码错误';

        $validator = Validator::make ( Input::all(), $rules, $messages );
        if ($validator->fails()) {
            // the given data did not pass validation
            return $this->makeView(
                'errors.400', 
                $validator->errors(),
                400
            );
        }

        try {
            $this->user->phone = $phone;
            $this->user->save ();
        } catch(Exception $ex) {
            Log::error($ex);
            return $this->makeView(
                'errors.503', 
                '咨询律师失败，请稍后再试。',
                503
            );
        }
        return $this->makeView('center.update_phone', '成功更改电话');
    }
    
    /**
     * 更改密码
     */
    public function resetPass() {
        $this->user->load('lawyer');
        $id = $this->user->id;
        if (Input::server ( 'REQUEST_METHOD' ) == 'POST') {
            $posts = Input::all();

            // old password should match the existing value
            Validator::extend ( 'old_password', function ($attr, $value, $parameters) use( $id ) {
                $credentials = array (
                    'id' => $id,
                    'password' => $value
                );
                return Auth::validate($credentials);
            } );

            // old password and new password should not be the same
            Validator::extend ( 'new_password_diff', function ($attr, $value, $parameters) use( $posts ) {
                return ($posts['old_password'] != $posts['new_password']);
            } );

            // the two new passes should be the same
            Validator::extend ( 'new_passwords_match', function ($attr, $value, $parameters) use( $posts ) {
                return ($posts['new_password'] == $posts['new_password_retype']);
            } );

            $rules['old_password']='required|old_password';
            $rules['new_password']='required|between:6,18|new_password_diff';
            $rules['new_password_retype']='required|new_passwords_match';

            $messages = array(
                'old_password.required' => '请填写原始密码',
                'new_password.required' => '请填写新密码',
                'new_password.new_password_diff' => '新密码不可以和旧密码一样',
                'new_password_retype.required' => '请再填写一次新密码',
                'old_password.old_password' => '原始密码填写不正确',
                'new_password.between' => '新密码格式不正确',
                'new_password_retype.new_passwords_match' => '请确保两次输入的新密码是一致的',
            );
            
            $validator = Validator::make ( $posts, $rules, $messages );
            if ($validator->fails()) {
                // the given data did not pass validation
                return $this->makeView(
                    'errors.400', 
                    $validator->errors(),
                    400
                );
            }

            try {
            	$oldPwd = $this->user->password;
                $this->user->password = $posts ['new_password'];
                $this->user->save ();
                //同步修改环信密码
                $newPwd = $this->user->password;
                $result = new Easemob();
                $options = array(
                		'username' => $this->user->id,
                		'password' => $oldPwd,
                		'newpassword' => $newPwd
                );
                $result_re = $result->editPassword($options);
            } catch(Exception $ex) {
                Log::error($ex);
                return $this->makeView(
                    'errors.503', 
                    '咨询律师失败，请稍后再试。',
                    503
                );
            }
            return $this->makeView('center.reset_pass', '成功更改密码');
        } else {
            return $this->makeView('center.reset_pass');
        }
    }
    
    /**
     * 我的订单-待付款
     */
    public function orderCart() {
    	try{
    		$order = Order::getOrder(Order::STATE_INIT);
    	}catch(Exception $ex) {
    		Log::error($ex);
    		return $this->makeView(
    				'errors.503',
    				'服务器暂时无法响应，请稍后再试。',
    				503
    		);
    	}
    	return $this->makeView('center.order.cart', $order);
    }
    
    public function orderIncomplete() {
    	try{
    		$order = Order::getOrder(Order::STATE_PAID);
    	}catch(Exception $ex) {
    		Log::error($ex);
    		return $this->makeView(
    				'errors.503',
    				'服务器暂时无法响应，请稍后再试。',
    				503
    		);
    	}
    	return $this->makeView('center.order.incomplete', $order);
    }
    
    
    public function orderWaitForComment() {
    	try{
    		$order = Order::getOrder(Order::STATE_DONE);
    	}catch(Exception $ex) {
    		Log::error($ex);
    		return $this->makeView(
    				'errors.503',
    				'服务器暂时无法响应，请稍后再试。',
    				503
    		);
    	}
    	$this->makeView('center.order.waitforcomment', $order);
        $this->layout->content = View::make('center.order.waitforcomment');
    }
    
    
    public function orderComplete() {
    	try{
    		$order = Order::getOrder(Order::STATE_DONE);
    	}catch(Exception $ex) {
                Log::error($ex);
                return $this->makeView(
                    'errors.503', 
                    '服务器暂时无法响应，请稍后再试。',
                    503
                );
            }
            $this->makeView('center.order.complete', $order);
    }

    public function view($id) {
        $order = Order::find($id);
        $orderArr = [
            'id' => 1,
            'order_no' => 1234,
            'order_status' => Order::STATE_DONE,
            'order_price' => 12334,
            'product_img' => UtilsHelper::getImage('test', "img/dfimg.png"),
            'product_qty' => 3,
            'product_name' => "企业法律顾问-钻石卡",
            'created_at' => '2015-10-29 09:51:19',
            'updated_at' => '2015-10-30 09:51:19'
        ];
        return $this->makeView('center.order.view',$orderArr);
    }

   
    // 律师的个人中心
    public function customerOrdered() {
    	$this->layout->content = View::make('center.customer_ordered');
    }
    public function customerFollowed() {
    	$this->layout->content = View::make('center.customer_followed');
    }
    public function customerConsulted() {
    	$this->layout->content = View::make('center.customer_consulted');
    }
    
    /**
     * 把相关的评论以及评论的用户加到咨询的列表中去
     */
    protected function addComments($questions) {
        foreach($questions as $key => $question) {
            $comments = Comment
                ::leftJoin('user', 'user.id', '=', 'comments.creator_id')
                ->select(
                    'comments.id',
                    'comments.content',
                    'user.realname as creator_realname',
                    'user.avatar as creator_avatar',
                    'user.id as creator_id',
                    'comments.created_at'
                )
                ->where('comments.post_id', $question['id'])
                ->orderBy('created_at', 'DESC')
                ->get();
            $question['comments'] = $comments->toArray();
            $questions[$key] = $question;
        }
        return $questions;
    }
    
    /**
     * 我的跟帖
     */
    public function blogReply(){
    	
    	$input = Input::all();
    	$page = Input::get('page', 1);
    	$rows_per_page = Input::get('rows_per_page', PaginationHelper::ROWS_PER_PAGE);
    	$offset = ($page-1) * $rows_per_page;
    	$orderby = 'created_at';
    	$direction = 'DESC';
    	$rules = array (
    			'page' => 'numeric|min:1',
    			'rows_per_page' => 'numeric|min:1',
    	);
    	$messages = array(
    			'page.numeric' => 'page需要是数字',
    			'rows_per_page.numeric' => 'rows_per_page需要是数字'
    	);
    	$validator = Validator::make ( $input, $rules, $messages );
    	if ($validator->fails()) {
    		// the given data did not pass validation
    		return $this->makeView(
    				'errors.400',
    				$validator->errors(),
    				400
    		);
    	}
    	
    	$myReplys = Article::leftjoin('evaluate', 'articles.id', '=', 'evaluate.item_id')
			->leftjoin('user', 'user.id', '=', 'articles.creator_id')
			->select(
					'articles.id as article_id',
					'articles.law_cat',
					'articles.img',
					'articles.title',
					'articles.info',
					'articles.hits',
					'articles.comments as comment_count',
					'articles.likes',
					'articles.downs',
					'articles.creator_id',
					'articles.created_at',
					'articles.collects_count',
					'articles.creator_id',
					'evaluate.comment',
                    'user.id as creator_id',
					'user.realname as creator_realname',
					'user.avatar as creator_avatar'
				)
			->where('evaluate.creator_id', Auth::user()->id)
			->where('evaluate.type', Evaluate::TYPE_ARTICLE)
			->take($rows_per_page)
			->skip($offset)
			->get();
        $articleArr = $myReplys->toArray();
        foreach($articleArr as &$article) {
            $article['creator_avatar'] = UtilsHelper::getImage($article['creator_avatar'], "img/dfimg.png");
        }
    	return $this->makeView('center.customer.blogreplies', $articleArr, 200);
    }
}
